package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author 小坏
 * @Date 2021/2/4 16:23
 * @Version 1.0
 * @program: 父工程 gulimall 万物起源之地
 */

@Configuration
public class GuliFeignConfig {

    /**
     * 调用feign之前都先调用拦截器
     *
     * @return
     */

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                /**
                 * 进行这一步的时候就可以把之前的请求头设置到新的里面
                 *          public OrderConfirmVo confirmOrder() {
                 */
                //获取当前请求的所有属性
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

                if (attributes != null) {
                    //TODO 现在无需共享数据、需要判断一下、未登录不能获取
                    System.out.println("RequestInterceptor线程。。。" + Thread.currentThread().getId());
                    HttpServletRequest request = attributes.getRequest(); //老请求
                    //1、运行异步任务、这个拦截器总是执行、实现类OrderServiceImpl
                    if (request != null) {
                        //同步请求头数据Cookie
                        String cookie = request.getHeader("Cookie");
                        //给新请求同步了老请求的cookie
                        template.header("Cookie", cookie);
                    }

                }

            }
        };
    }
}
